import 'package:dy_download_utils/controller_dy.dart';
import 'package:dy_download_utils/dailogs.dart';
import 'package:dy_download_utils/page_info.dart';
import 'package:dy_download_utils/snackbar/snackbar_request_state_builder.dart';
import 'package:dy_download_utils/state_request.dart';
import 'package:dy_download_utils/utils_system.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text(
            '抖音视频下载',
            style: TextStyle(
              fontSize: 22.0,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
            ),
          ),
          centerTitle: true,
          backgroundColor: Colors.transparent,
          elevation: 0.0,
        ),
        body: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                margin: const EdgeInsets.only(top: 10.0),
                padding:
                    const EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  '有水印（速度较快）',
                  style: TextStyle(
                    fontSize: 16.0,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
              ),
              Container(
                margin: const EdgeInsets.all(5.0),
                child: Container(
                  padding: const EdgeInsets.all(2.0),
                  child: Center(
                    child: buildTextField(0),
                  ),
                ),
              ),
              Container(
                margin: const EdgeInsets.only(top: 10.0),
                padding:
                    const EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
                alignment: Alignment.centerLeft,
                child: Text(
                  '无水印（速度较慢）',
                  style: TextStyle(
                    fontSize: 16.0,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
              ),
              Container(
                margin: const EdgeInsets.all(5.0),
                child: Container(
                  padding: const EdgeInsets.all(2.0),
                  child: Center(
                    child: buildTextField(1),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildTextField(int index) {
    return Obx(() {
      var value = DyController.to.shareTextLive.value;
      if (value.isNotEmpty) {
        if (index == 0) {
          DyController.to.urlC0.text = value;
        } else if (index == 1) {
          DyController.to.urlC1.text = value;
        }
      }
      return TextField(
        controller: index == 0 ? DyController.to.urlC0 : DyController.to.urlC1,
        maxLines: 1,
        style: TextStyle(
          fontSize: 16.0,
        ),
        textInputAction: TextInputAction.search,
        decoration: InputDecoration(
          //这行代码是关键，设置这个之后，居中
          contentPadding: EdgeInsets.all(12),
          fillColor: Colors.transparent,
          filled: true,
          isCollapsed: true,
          hintText: '输入抖音视频链接',
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(5.0),
            borderSide: const BorderSide(color: Colors.green, width: 1.0),
          ),
          prefixIcon: const Icon(IconData(0xe8db, fontFamily: 'MIcons')),
          suffixIcon: GestureDetector(
            child: const Icon(IconData(0xe600, fontFamily: 'MIcons')),
            onTap: () {
              SystemUtils.hideSoftKeyboard(Get.context!);
              Future.delayed(const Duration(milliseconds: 300), () {
                requestDyDownloadInfo(index);
              });
            },
          ),
        ),
        onSubmitted: (key) {
          SystemUtils.hideSoftKeyboard(Get.context!);
          Future.delayed(Duration(milliseconds: 300), () {
            requestDyDownloadInfo(index);
          });
        },
        onChanged: (key) {},
      );
    });
  }

  void requestDyDownloadInfo(int index) {
    String totalDyUrl =
        index == 0 ? DyController.to.urlC0.text : DyController.to.urlC1.text;

    RegExp reg = RegExp('https(.*)/');
    String? dyUrl = reg.stringMatch(totalDyUrl);

    if (dyUrl == null) {
      popDialog(
          Container(
            child: Text(
              '解析抖音链接失败',
              style: TextStyle(
                fontSize: 18.0,
                color: Colors.black87,
              ),
            ),
          ), onPositiveTap: () {
        Get.back();
      });
      return;
    }

    var result = DyController.to.requestInfoResult.value;
    if (result.url == dyUrl) {
      Get.to(InfoPage(index, result.data!));
      return;
    }

    DyController.to.requestDownloadWebPage(index, dyUrl);
    Get.showSnackbar(buildRequestGetBar(
      SnackContentConfig(
        waitingMessage: '正在解析…',
        doneMessage: '解析完成。',
        errMessage: '解析失败。',
      ),
      () {
        return DyController.to.requestInfoState.value;
      },
      () {
        return DyController.to.requestInfoResult.value;
      },
      snackbarStatus: (status) {
        if (status == SnackbarStatus.CLOSING) {
          var infoResult = DyController.to.requestInfoResult.value;
          if (infoResult.err == RequestState.SUCCESS) {
            Get.to(InfoPage(index, infoResult.data!));
          } else {
            Get.rawSnackbar(
              backgroundColor: Get.theme.primaryColor,
              messageText: Text(
                infoResult.errMsg!,
                style: TextStyle(
                  color: Get.theme.scaffoldBackgroundColor,
                ),
              ),
            );
          }
        }
      },
    ));
  }
}
